package com.xjscrm.console.chat.mq.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.uzai.mobile.collect.api.dto.MicaTransDto;
import com.uzai.mobile.collect.api.dto.msg.MicaFriendTalkMsg;
import com.uzai.mobile.collect.api.dto.trigger.MicaTriggerConversationTalkMsg;
import com.uzai.mobile.collect.api.enums.MicaMsgSource;
import com.uzai.mobile.collect.api.enums.MicaMsgType;
import com.xjscrm.common.entity.WwDevice;
import com.xjscrm.console.chat.enums.ChatTalkRecordSource;
import com.xjscrm.console.chat.mq.MQSender;
import com.xjscrm.console.chat.mq.MsgHandler;
import com.xjscrm.console.chat.mq.dto.DispatchDTO;
import com.xjscrm.console.entity.ChatTalkRecord;
import com.xjscrm.console.entity.ChatTalkSession;
import com.xjscrm.console.entity.ChatTalkSessionStaffRel;
import com.xjscrm.console.service.customer.chat.ChatTalkRecordService;
import com.xjscrm.console.service.customer.chat.ChatTalkSessionStaffRelService;
import com.xjscrm.console.service.customer.wwDevice.WwDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Objects;

/**
 * @author mingyang.chen create in 2024/3/11 18:14
 */
@Component
@Slf4j
public class ServerTalkMsgHandler extends TalkMsgHandler implements MsgHandler<MicaTriggerConversationTalkMsg> {

    @Autowired
    private ChatTalkRecordService chatTalkRecordService;
    @Autowired
    private WwDeviceService wwDeviceService;
    @Autowired
    private ChatTalkSessionStaffRelService chatTalkSessionStaffRelService;

    @Override
    public MicaMsgType msgType() {
        return MicaMsgType.SERVER_TALK_MSG;
    }

    @Override
    public Class<MicaTriggerConversationTalkMsg> msgClass() {
        return MicaTriggerConversationTalkMsg.class;
    }

    @Override
    @Transactional
    public void doHandle(MicaTriggerConversationTalkMsg req) {

        log.info("ServerTalk: {}", JSON.toJSONString(req));
        // 处理的消息
        ArrayList<Integer> validCode = Lists.newArrayList(MicaMsgSource.FAQ_REPLY.getCode(), MicaMsgSource.NEW_CUSTOMER_OPERATOR.getCode(), MicaMsgSource.KEYWORD_PULL_GROUP.getCode());
        //
        if (Objects.isNull(MicaMsgSource.getByValue(req.getSource())) || !validCode.contains(req.getSource())) {
            log.error("消息来源: {}", req.getSource());
            return;
        }

        MicaTransDto micaTransDto = baseCache.get();
        Long merId = micaTransDto.getMerId();
        String deviceId = micaTransDto.getDeviceId();
        Integer deviceType = micaTransDto.getDeviceType();

        MicaFriendTalkMsg micaFriendTalkMsg = new MicaFriendTalkMsg();
        micaFriendTalkMsg.setConversationId(req.getWxId());
        micaFriendTalkMsg.setSendWxId(deviceId);
        micaFriendTalkMsg.setMsgType(req.getContentType());
        micaFriendTalkMsg.setContent(req.getContent());
        micaFriendTalkMsg.setGroup(req.getGroup());
        micaFriendTalkMsg.setSendTime(System.currentTimeMillis() / 1000L);

        String conversationId = micaFriendTalkMsg.getConversationId();
        if (!ObjectUtils.allNotNull(conversationId, merId, deviceType) || StringUtils.isBlank(deviceId)) {
            log.error("ServerTalk info is illegal");
            return;
        }

        WwDevice wwDevice = wwDeviceService.getByDeviceId(merId, deviceId);
        if (Objects.isNull(wwDevice)) {
            log.error("ServerTalk device not found : {}", deviceId);
            return;
        }
        micaFriendTalkMsg.setSendWxId(wwDevice.getDeviceId());
        micaFriendTalkMsg.setSendNickName(wwDevice.getDeviceName());

        // 新增回话, 如何不存在
        ChatTalkSession talkSession;
        ChatTalkRecord chatTalkRecord;
        try {
            long talkRecordId = IdUtil.getSnowflakeNextId();
            //
            talkSession = super.addSessionIfAbsentWithUpdate(merId, talkRecordId, wwDevice, micaFriendTalkMsg);
            if (Objects.isNull(talkSession)) {
                return;
            }
            //
            chatTalkRecord = super.build(micaFriendTalkMsg, talkSession);
            chatTalkRecord.setId(talkRecordId);
            chatTalkRecord.setSource(ChatTalkRecordSource.reply.getCode());
            // 新增聊天记录
            chatTalkRecordService.add(chatTalkRecord);
            log.info("ServerTalk session and record is save success; next dispatch message: talkSessionId: {}; talkRecordId: {}", talkSession.getId(), chatTalkRecord.getId());

            ChatTalkSessionStaffRel byConvIdAndSessionId = chatTalkSessionStaffRelService.getByConvIdAndSessionId(merId, talkSession.getConversationId(), talkSession.getId());
            //
            if (Objects.nonNull(byConvIdAndSessionId)) {
                DispatchDTO dispatchDTO = new DispatchDTO();

                dispatchDTO.setMerId(merId);
                dispatchDTO.setDeviceUniqueId(wwDevice.getId());
                dispatchDTO.setTalkSessionId(talkSession.getId());

                MQSender.sendMQMsg("XJ_WW_DISPATCH_TOPIC", dispatchDTO);
            }
        } catch (Exception e) {
            log.error("ServerTalk save session and record is fail", e);
            throw e;
        }
    }
}
